<!-- components/TkiQrCode/TkiQrCode.vue -->
<!-- 组件说明：使用的依赖库 "weapp-qrcode": "^1.0.0" -->

<template>
	<view
		:style="{ width: size + 'px', height: size + 'px' }"
		class="container"
	>
		<canvas
			:canvas-id="canvasId"
			:id="canvasId"
			:width="canvasWidth"
			:height="canvasHeight"
			class="qrCodeCanvas"
		/>
	</view>
</template>

<script>
// 引入 weapp-qrcode（支持小程序和 H5 和 APP ）
import makeQRCode  from 'weapp-qrcode';

export default {
	name: 'TkiQrCode',
	props: {
		value: { type: String, required: true },
		size: { type: Number, default: 200 },
		canvasId: { type: String, default: 'tki-qrcode-canvas' },
		margin: { type: Number, default: 1 },
		background: { type: String, default: '#FFFFFF' },
		foreground: { type: String, default: '#000000' },
		autoMake: { type: Boolean, default: true },
		logo: { type: String, default: '' },
		logoSize: { type: Number, default: 0.2 },
		logoBackgroundColor: { type: String, default: null },
		logoCornerRadius: { type: Number, default: 4 },
	},

	data() {
		return {
			dpr: 1,
			canvasWidth: this.size,
			canvasHeight: this.size,
		};
	},

	mounted() {
		this.init();
	},

	methods: {
		init() {
			const res = uni.getSystemInfoSync();
			this.dpr = res.pixelRatio ?? 1;
			this.canvasWidth = this.size * this.dpr;
			this.canvasHeight = this.size * this.dpr;

			if (this.autoMake) {
				this.$nextTick(() => {
					setTimeout(() => {
						this.make();
					}, 300);
				});
			}
		},

		async make() {
			if (!this.value) return;

			const ctx = uni.createCanvasContext(this.canvasId, this);

			try {
				// 清空画布
				ctx.clearRect(0, 0, this.size, this.size);
				ctx.setFillStyle(this.background);
				ctx.fillRect(0, 0, this.size, this.size);

				// 使用 weapp-qrcode 生成真实二维码
				const qrRes = await makeQRCode({
					text: this.value,
					width: this.size,
					height: this.size,
					colorDark: this.foreground,
					colorLight: this.background,
					padding: this.margin * 4, // margin 转 px
					canvasId: this.canvasId,
					isDrawOnCanvas: false, // 我们自己 draw
				});
console.log('qrRes:', qrRes);
				// 绘制二维码图像
				ctx.drawImage(qrRes.tempFilePath, 0, 0, this.size, this.size);

				// 绘制 Logo（如果存在）
				if (this.logo) {
					await this.drawLogo(ctx);
				}

				// 最终绘制
				ctx.draw(false, () => {
					this.$emit('made');
					this.save();
				});
			} catch (err) {
				console.error('二维码生成失败:', err);
				this.$emit('error', err);
			}
		},

		async drawLogo(ctx) {
			let tmpPath = this.logo;
			try {
				if (this.logo.startsWith('http')) {
					const download = await uni.downloadFile({ url: this.logo });
					tmpPath = download.tempFilePath;
				}

				const marginPx = this.margin * 4; // 和生成时一致
				const contentSize = this.size - 2 * marginPx;
				const logoWidth = contentSize * this.logoSize;
				const logoHeight = contentSize * this.logoSize;
				const logoX = marginPx + (contentSize - logoWidth) / 2;
				const logoY = marginPx + (contentSize - logoHeight) / 2;

				// 绘制背景（可选）
				if (this.logoBackgroundColor) {
					ctx.setFillStyle(this.logoBackgroundColor);
					this.roundRect(
						ctx,
						logoX,
						logoY,
						logoWidth,
						logoHeight,
						this.logoCornerRadius
					);
					ctx.fill();
				}

				// 绘制 Logo
				ctx.drawImage(tmpPath, logoX, logoY, logoWidth, logoHeight);
			} catch (err) {
				console.error('Logo 绘制失败:', err);
				this.$emit('logoError', err);
			}
		},

		roundRect(ctx, x, y, w, h, r) {
			r = Math.min(r, w / 4, h / 4);
			ctx.beginPath();
			ctx.moveTo(x + r, y);
			ctx.arcTo(x + w, y, x + w, y + h, r);
			ctx.arcTo(x + w, y + h, x, y + h, r);
			ctx.arcTo(x, y + h, x, y, r);
			ctx.arcTo(x, y, x + w, y, r);
			ctx.closePath();
		},

		save() {
			uni.canvasToTempFilePath({
				canvasId: this.canvasId,
				x: 0,
				y: 0,
				width: this.size,
				height: this.size,
				destWidth: this.size * this.dpr,
				destHeight: this.size * this.dpr,
				success: (res) => {
					this.$emit('result', res.tempFilePath);
				},
				fail: (err) => {
					console.error('导出失败:', err);
					this.$emit('result', null);
				},
			}, this);
		},
	},
};
</script>

<style scoped>
.container {
	position: relative;
	display: inline-block;
}
.qrCodeCanvas {
	width: 100%;
	height: 100%;
}
</style>